package com.example.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.dto.PermissionDirectoryDto;
import com.example.domain.vo.PermissionDirectoryResVO;
import com.example.entity.PermissionDirectory;
import com.example.mapper.PermissionDirectoryMapper;
import com.example.service.PermissionDirectoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 存储引擎为InnoDB，字符集为utf8(PermissionDirectory)表服务实现类
 *
 * @author makejava
 * @since 2025-02-23 23:17:57
 */
@Service
public class PermissionDirectoryServiceImpl extends ServiceImpl<PermissionDirectoryMapper,PermissionDirectory> implements PermissionDirectoryService {

    @Autowired
    private PermissionDirectoryMapper permissionDirectoryMapper;
    @Override
    public List<PermissionDirectoryResVO> selectList() {
        List<PermissionDirectoryResVO> directoryTree = new ArrayList<>();
        List<PermissionDirectory> menuList = permissionDirectoryMapper.selectList();
        if (CollectionUtils.isNotEmpty(menuList)){
            List<PermissionDirectoryResVO> pdr = menuList.stream().map(PermissionDirectory -> {
                PermissionDirectoryResVO permissionDirectoryResVO = new PermissionDirectoryResVO();
                BeanUtils.copyProperties(PermissionDirectory, permissionDirectoryResVO);
                return permissionDirectoryResVO;
            }).collect(Collectors.toList());
            pdr.forEach(e ->{
                List<PermissionDirectoryResVO> pdrList = getChildrenList(e.getId(),pdr);
                e.setSetAuthMenuList(pdrList != null ? pdrList :null);
            });
            List<PermissionDirectoryResVO> parentNodes = pdr.stream().filter(e -> e.getParentId().equals(0)).collect(Collectors.toList());
            directoryTree.addAll(parentNodes);
        }
        return directoryTree;
    }

    /**
     * 获取全部子集
     * @param id
     * @param list
     * @return
     */
    public static List<PermissionDirectoryResVO> getChildrenList(Integer id, List<PermissionDirectoryResVO> list){
        return list.stream().filter(t-> t.getParentId().equals(id)).collect(Collectors.toList());
    }

    @Override
    public void add(PermissionDirectoryDto dto) {
        this.save(dto);
        /**
         * 递归添加子菜单
         */
        if (dto.getChildrenList() != null && !dto.getChildrenList().isEmpty()){
            for (PermissionDirectoryDto children : dto.getChildrenList()){
                children.setParentId(dto.getId());
                add(children);
            }
        }
    }

}
